<template>
  <template v-if="role.role_name !== 'User' && skillList.length > 0">
    <SkillList
      :list="skillList"
      :selectSkill="selectSkill"
      @change="handleChage"
      @placeOrder="handlePlaceOrder"
    />
    <GameInfo :selectSkill="selectSkill" />
    <UserReview :id="selectSkillId" />
    <Drawer v-model:visible="drawerShow" :selectSkill="selectSkill" :user-info="role" />
  </template>
  <template v-else>
    <Empty :role="role" />
  </template>
</template>
<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import SkillList from './skills-list.vue'
import GameInfo from './game-info.vue'
import Empty from './empty.vue'
import UserReview from './user-review.vue'
import { getSkills } from '@/api/game'
import emitter from '@/utils/mitt'
import Drawer from './drawer.vue'

const route = useRoute()
const userId = Number(route.params.id)
const skillList = ref([])
const selectSkillId = ref(-1)
const drawerShow = ref(false)
const selectSkill = computed(() => {
  return skillList.value.find((item) => item.id === selectSkillId.value) || {}
})
emitter.on('addSkill', (skills) => {
  if (!selectSkill.value) {
    selectSkillId.value = skills.id
  }
  skillList.value.push(skills)
})
emitter.on('updateSkill', (skills) => {
  skillList.value = skillList.value.map((item) => {
    if (item.id === skills.id) {
      return skills
    }
    return item
  })
})
const handlePlaceOrder = () => {
  console.log('place order')
  drawerShow.value = true
}
const handleChage = (id) => {
  selectSkillId.value = id
}
onMounted(() => {
  getSkills(userId).then((res) => {
    skillList.value = res
    selectSkillId.value = res && res[0]?.id
  })
})
onUnmounted(() => {
  emitter.off('addSkill')
  emitter.off('updateSkill')
})
defineProps(['role'])
</script>
<style lang="less" scoped></style>
